<?php

/*
 * This file is part of the symfony package.
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 * 
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Create a new user.
 *
 * @package    symfony
 * @subpackage task
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author     Jonathan H. Wage <jonwage@gmail.com>
 * @version    SVN: $Id: sfGuardCreateUserTask.class.php 28922 2010-03-31 13:53:45Z noel $
 */
class sfGuardCreateUserTask extends sfBaseTask
{
	protected $i18n;
	
  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->addArguments(array(
      new sfCommandArgument('email_address', sfCommandArgument::REQUIRED, 'The email address'),
      new sfCommandArgument('username', sfCommandArgument::REQUIRED, 'The username'),
      new sfCommandArgument('password', sfCommandArgument::REQUIRED, 'The password'),
      new sfCommandArgument('language', sfCommandArgument::OPTIONAL, 'User language (es_ES, en_US)',"es_ES"),
      new sfCommandArgument('type', sfCommandArgument::OPTIONAL, 'Type of user ("normal" user or "place" user)',"user"),
      new sfCommandArgument('application', sfCommandArgument::OPTIONAL, 'The application name','ui')
    ));

    $this->addOptions(array(
      new sfCommandOption('id', null, sfCommandOption::PARAMETER_OPTIONAL, 'The user id', null),
      new sfCommandOption('is-super-admin', null, sfCommandOption::PARAMETER_NONE, 'Whether the user is a super admin', null),
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', null),
      new sfCommandOption('firstname', null, sfCommandOption::PARAMETER_OPTIONAL, 'The firstname', null),
      new sfCommandOption('lastname', null, sfCommandOption::PARAMETER_OPTIONAL, 'The lastname', null),
      new sfCommandOption('country', null, sfCommandOption::PARAMETER_OPTIONAL, 'The country code', null),
      new sfCommandOption('birthday', null, sfCommandOption::PARAMETER_OPTIONAL, 'The birthday', null),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      
    ));

    $this->namespace = 'guard';
    $this->name = 'create-user';
    $this->briefDescription = 'Creates a user';

    $this->detailedDescription = <<<EOF
The [guard:create-user|INFO] task creates a user:

  [./symfony guard:create-user mail@example.com fabien password Fabien POTENCIER|INFO]
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
	$databaseManager = new sfDatabaseManager($this->configuration);

    if(!LdapLogin::createUser($arguments['username'],$arguments['password']))
        throw new Exception('User already exists in LDAP database');
    
    $user = new sfGuardUser();

    if($options['id'])
    	$user->setId($options['id']);
    $user->setUsername($arguments['username']);
    $user->setEmailAddress($arguments['email_address']);
    $user->setPassword($arguments['password']);
    
    
    $user->setFirstname($options['firstname']);
    $user->setLastname($options['lastname']);
    
    
    $user->setIsActive(true);
    $user->setIsSuperAdmin($options['is-super-admin']);
    //Language
    $translator = $this->getI18N($arguments['language']);
    $lang = Doctrine::getTable("language")->findByLanguageCode($arguments['language'])->getFirst();
        $user->setLanguageId($lang->getLanguageId());
    $user->save();

    
    //Main aclGroup
    $aclGroup= new AclGroup();
    $aclGroup->setGroupName($translator->__("Friends"));
    $aclGroup->setOwner($user);
    $aclGroup->save();
    $user->setMainGroup($aclGroup);
    
    //Main album
    $album = new Album();
    $album->setName($translator->__("All photos"));
    $album->setOwner($user);
    $album->save();
    $user->setMainAlbum($album);

    $user->save();

    
    //Main private message directory
    $directory = new PrivateMessageDirectory();
    $directory->setName($translator->__("Inbox"));
    $directory->setUser($user);
    $directory->save();
    $user->setMainPrivateMessagesDirectory($directory);
    //Main private message sent directory
    $directory = new PrivateMessageDirectory();
    $directory->setName($translator->__("Sent"));
    $directory->setUser($user);
    $directory->save();
    $user->setMainPrivateMessagesSentDirectory($directory);
    
    $user->save();
        
    if($arguments['type'] == "site"){
    	$user->addGroupByName("site");
    	
        $profile = new GroupProfile();
            $profile->setVisits(0);
            $profile->setUserId($user->getId());
            $profile->save();
            
        //Default placeprofile interests
            $interestsList = array("Description");
            foreach($interestsList as $interestName){
                $interest = new Interest();
                    $interest->setName($interestName);
                    $interest->setGroupProfileId($profile->getId());
                    $interest->save();  
            }
    }else{
        //Normal user
        $user->addGroupByName("people");
            //Profile
            $profile = new Profile();
            $profile->setVisits(0);
            $profile->setUserId($user->getId());
            $profile->setBirthday($options['birthday']);
            if($options['country']){
	            	$country = Doctrine::getTable("Country")->findByCode($options['country'])->getFirst();
	            	if(is_object($country))
	            		$profile->setCountry($country);
	            	else{
	            		$user->delete();
	            		LdapLogin::removeUser($user->getUsername());
	            		throw new Exception("Invalid country");
	            	} 
            }
            $profile->save();
            
                

            //Allow friends to access main profile
            $permission = new AclProfileGroup();
            $permission->setProfileId($user->getId());
            $permission->setGroupId($aclGroup->getGroupId());
            $permission->setReadGranted(true);
                $permission->setReadDenied(false);
                $permission->setWriteGranted(true);
                $permission->setWriteDenied(false);
                $permission->save();
            //
            //Allow friends to access main album
            $permission = new AclAlbumGroup();     
            $permission->setAlbumId($album->getAlbumId());
            $permission->setGroupId($aclGroup->getGroupId());
            $permission->setReadGranted(true);
                $permission->setReadDenied(false);
                $permission->setWriteGranted(true);
                $permission->setWriteDenied(false);
                $permission->save();
            //
            //Default profile interests
            $interestsList = array($translator->__("Hobbies"),$translator->__("Music"),$translator->__("Films"),$translator->__("Books"),$translator->__("Videogames"),$translator->__("About me"));
            foreach($interestsList as $interestName){
                $interest = new Interest();
                    $interest->setName($interestName);
                    $interest->setProfileId($profile->getId());
                    $interest->save();  
            }
    }

                //Install the default plugins
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="photoTags"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="albumList"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="aboutMe"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="accountActions"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="photoOptions"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="notifications"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="privateMessagesDirectories"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="calendarOptions"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="calendarNotificator"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="profilePhotos"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="profileFriends"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="profileMutualFriends"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="searchOptions"');
                $this->runTask('wixet:install-widget', '--user='.$user->getUsername().' --widget="forumList"');
                
                //Emoticons
                $defaultEmoticons = array('10995b9bdcebd4c9bcee3f4ab63d43ad','241b7e62b7f420046d679035545afa02','26738211281f277d670cf2b20dff8388',
				'2ae3fd1a90c1f267c5d2694347d1afa3','2fac572152d532a9bf14831ca4094ef0','48d612cb39ee15465c14b341caeefbd4','49ebbef71af56d2b016df6b4671cee6f',
				'572cbda77f794eb69bb578fda651c604','5f7e1b80d4032bcc5e5b5fc065a9785d','7a68bcd1377c741c24ab3f5b34680b95','9094d91db616fe2ebfc1a041bdded147',
				'9251c3c578efa7d47a63a01568ad8de9','a2dc64b95620d0da658efb1e1b1bebd7','a6cd78d1ad58c70a2ba699388ab2d524','a8ca04fe952be71920e284b72d73ece2',
				'c56d531a1f939cf9992f3531ecb0e249','e6a0224065407ab085d30e273f85e381','f984504dd2d7158fbeb8315d1f37a490');
                foreach($defaultEmoticons as $emoticonId){
                	
	                $emoticon = new EmoticonUser();
	                $emoticon->setEmoticonId($emoticonId);
	                $emoticon->setUserId($user->getId());
	                $emoticon->save();
                }
                //Sounds
                $defaultSounds = array('08c6f6c588dcc5e9c5c654bb25a4397e','0b1e0de1b261b9387a1274dc68104ac5','1716a50c1e08b63c672f9d28b2334e49','1dcfbdbc154d1ba57d400f04ef6ea8a1',
                '267917b10957e8c13f63a22af470bdce','37a1a232113b91337f89e144db96953f','388759c6d3d4297a49890d5b47ad573b','6fa8f24a39701de99da8a9b2c085ee3','827811f71e13b1e14b844ae04c3c62b4',
                '888bc9015075644ea210884c88a03f08','979a386f33c96ae927cb55e806f7db08','9de41a0c3a4a0cb9d0685e4e241853f5','ba3807fb583f82be0a33457f88f29a5b','05c04a1851ceaf091c72919e347ce68',
                'ccaf0eafce551aa21517319771a340c7','cd5f1764617ba8563f79af54acef5029','defa6d743b50b72326440ef4461014cc','df930bf50224cc191ab79b29363d4571','e6b072530bb6b5c175fd2d99470b6e84');
                foreach($defaultSounds as $soundId){
                	$soundUser = new SoundUser();
	                $soundUser->setSoundId($soundId);
	                $soundUser->setUserId($user->getId());
	                $soundUser->save();
                }
    

  }
  
    protected function getI18N($culture = 'en')
        {
          if (!$this->i18n)
          {
            $config = sfFactoryConfigHandler::getConfiguration($this->configuration->getConfigPaths('config/factories.yml'));
            $class  = $config['i18n']['class'];
            $this->i18n = new $class($this->configuration, null, $config['i18n']['param']);
          }
         
          $this->i18n->setCulture($culture);
         
          return $this->i18n;
        }
  
}